﻿@using Huirui.Cavan.Domain.MainBoundedContext.SalesModule
@model Huirui.Cavan.Presentation.ViewModel.SalesModule.ISalesOrderViewModel
@{
    Layout = null;
}
@using (Html.BeginForm(ActionConst.ADD, ControllerConst.SALESORDER))
{
    <div class="tool_bar">
        <input id="saleorder_save" type="submit" value="save" style="display: none;" />
        <input id="saleorder_reset" type="reset" style="display: none" />
        <input id="saleorder_query" type="submit" value="query" style="display: none;" />
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-save'"
            onclick="javascript:$('#saleorder_save').click()">保存</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add',disabled:true"
            onclick="javascript:$('#saleorder_reset').click()">新增</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-delete',disabled:true">删除</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-buy',disabled:true">生成采购订单</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-building',disabled:true">生成销售单</a>
        <a href="#" id="queryPurchaseOrder" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'">查询</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-print',disabled:true">打印</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-collapse'"
            onclick="toggleHeard()">折叠/展开</a>
    </div>
    <table class="form_heard">
        <tr>
            <td class="c100">
                <label>
                    订单日期:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.SaleDate, new { id = "saleDate", style = "height:18px", @class = "Wdate", onfocus = "WdatePicker({minDate:'%y-%M-#{%d+1}'})" })
            </td>
            <td class="c100">
                <label>
                    交货日期:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.DeliveryDate, new { id = "deliveryDate", style = "height:18px", @class = "Wdate", onfocus = "WdatePicker({minDate:'%y-%M-#{%d+1}'})" })
            </td>
            <td class="c100">
                <label>
                    客户订单号:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.CustomerOrderCode, new { id = "customerOrderCodeForSalesOrder" })
            </td>
            <td class="c10"></td>
            <td class="c100">
                <label>
                    销售订单号:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Id, new { id = "codeForSalesOrder" })
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    客户*:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Customer.Id, new { id = "customerCodeForSalesOrder" })
            </td>
            <td colspan="2">
                @Html.TextBoxFor(m => m.Item.Customer.Name, new { id = "customerNameForSalesOrder" })
            </td>
            <td class="c100">
                <label>
                    销售人员:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.SaleEmployee.Id, new { id = "saleEmployeeCodeForSalesOrder" })
                @Html.HiddenFor(m => m.Item.SaleEmployee.Name, new { id = "saleEmployeeNameForSalesOrder" })
            </td>
            <td class="c10"></td>
            <td class="c100">
                <label>
                    接单仓库:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.WareHouse.Id, new { id = "wareHouseAddressForSalesOrder" })
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    币别:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Currency, new { id = "currency" })
            </td>
            <td class="c100">
                <label>
                    汇率:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.CurrencyRate, new { id = "currencyRate" })
            </td>
            <td class="c100">
                <label>
                    税率:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.TaxRate, new { id = "taxRate" })
            </td>
            <td class="c10">@Html.Raw("%")</td>
            <td class="c100">
                <label>
                    开票类型:</label>
            </td>
            <td class="c160">
                @Html.DropDownListFor(m => m.CheckType, typeof(SalesIdentifier.CheckType), new { id = "checkType" })
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    送货地址:</label>
            </td>
            <td colspan="4">
                @Html.TextBoxFor(m => m.Item.DeliveryAddress, new { id = "deliveryAddress" })
            </td>
            <td class="c160">
                <a>请选择常用送货地址</a>
            </td>
            <td class="c10"></td>
            <td class="c100">
                <a>审核状态:</a>
            </td>
            <td class="c160">
                <input type="text" />
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    备注:</label>
            </td>
            <td colspan="7">
                @Html.TextBoxFor(m => m.Item.Remark, new { id = "remark" })
            </td>
            <td class="c160">
                <a>请选择常用备注</a>
            </td>
        </tr>
    </table>
    @Html.HiddenFor(m => m.SalesOrderDetails, new { id = "salesOrderDetails" })
}
<table id="selectedStocksForSalesOrder" title="存货列表" toolbar="#sale_order_tb">
</table>
<div id="sale_order_tb">
    <a href="#" id="selectStockForSalesOrder" class="easyui-linkbutton" iconcls="icon-checked"
        plain="true" onclick="InitSelectStockForSales('stocksForSalesOrder');openWindow('selectStockWindowForSalesOrder')">选择商品</a>
</div>
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.STOCK, new { purpose = "ForSalesOrder" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.CUSTOMER, new { purpose = "ForSalesOrder" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.WAREHOUSE, new { purpose = "ForSalesOrder" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.EMPLOYEE, new { purpose = "ForSalesOrder" }); }

<script type="text/javascript">
    $(function () {
        var lastIndex;
        var purchaseOrderDetails;
        $('#selectedStocksForSalesOrder').datagrid({
            columns: [[
                { field: 'NoPrefixId', title: '存货编码', width: 100 },
                { field: 'Id', title: '存货编码', width: 100, hidden: true },
                { field: 'Name', title: '存货名称', width: 80 },
                { field: 'Specification', title: '规格', width: 60 },
                { field: 'UnitTransfer', title: '计量单位', width: 100 },
                { field: 'Number', title: '数量', width: 100, editor: { type: 'text' } },
                { field: 'AssistantNumber', title: '辅助数量', width: 100 },
                { field: 'StandardSalesPrice', title: '单价', width: 100 },
                { field: 'DiscountRate', title: '折扣率', width: 100 },
                { field: 'DiscountAmount', title: '折扣额', width: 80 },
                { field: 'SalesAmount', title: '销售额', width: 80 },
                { field: 'LocalCurrencySalesAmount', title: '本币销售额', width: 80 },
                { field: 'TaxRate', title: '税率', width: 80, editor: { type: 'text' } },
                { field: 'TaxAmount', title: '税额', width: 80 },
                { field: 'UnTaxAmount', title: '未税销售额', width: 80 },
                { field: 'Remark', title: '备注', width: 80 }
            ]]
        });

        $("#searchStockForSalesOrder").submit(function () {
            $("#stocksByCustomerForSalesOrder").val($("#customerCodeForSalesOrder").val());
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#stocksForSalesOrder').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        var currentIndex;
        var currentRow;
        var rowId;
        var number;
        var taxRate;

        $("#doSelectStockForSalesOrder").bind("click", function () {
            $('#selectedStocksForSalesOrder').datagrid('loadData', { total: 0, rows: [] });
            var rows = $('#stocksForSalesOrder').datagrid('getSelections');
            for (var i = 0; i < rows.length; i++) {
                insert(rows[i].NoPrefixId, rows[i].Id, rows[i].Name, rows[i].Specification, rows[i].UnitTransfer, 0, 0, rows[i].StandardSalesPrice, rows[i].DiscountRate, 0, 0, 0, 0, 0, 0, 'test');
            }
            closeWindow('selectStockWindowForSalesOrder')
        });

        function insert(noPrefixId, id, name, specification, unitTransfer, number, assistantNumber, standardSalesPrice, discountRate, discountAmount, salesAmount, localCurrencySalesAmount, taxRate, taxAmount, unTaxAmount, remark) {
            var rows = $('#selectedStocksForSalesOrder').datagrid('getRows');
            index = -1;
            if (rows.length == 0) {
                index = 0;
            }
            else {
                index = rows.length;
            }

            $('#selectedStocksForSalesOrder').datagrid('insertRow', {
                index: index,
                row: {
                    NoPrefixId: noPrefixId,
                    Id: id,
                    Name: name,
                    Specification: specification,
                    UnitTransfer: unitTransfer,
                    Number: number,
                    AssistantNumber: assistantNumber,
                    StandardSalesPrice: standardSalesPrice,
                    DiscountRate: discountRate,
                    DiscountAmount: discountAmount,
                    SalesAmount: salesAmount,
                    LocalCurrencySalesAmount: localCurrencySalesAmount,
                    TaxRate: taxRate,
                    TaxAmount: taxAmount,
                    UnTaxAmount: unTaxAmount,
                    Remark: remark
                }
            });
            $('#selectedStocksForSalesOrder').datagrid('selectRow', index);
            $('#selectedStocksForSalesOrder').datagrid('beginEdit', index);

            var ed = $('#selectedStocksForSalesOrder').datagrid('getEditors', index);
            for (var i = 0; i < ed.length; i++) {
                var e = ed[i];
                if (e.field == "Number") {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function () {
                        $('#selectedStocksForSalesOrder').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function () {
                        number = $(this).val();
                        currentIndex = $(this).attr("selectedStockRowIndex");
                        currentRow = $('#selectedStocksForSalesOrder').datagrid('getSelected');
                        rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "TaxRate") {
                                taxRate = $(this).find("input").val();
                            }
                        });
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "SalesAmount") {
                                $(this).find("div").html(number * currentRow.StandardSalesPrice * (1 - currentRow.DiscountRate / 100));
                            }
                            if ($(this).attr("field") == "DiscountAmount") {
                                $(this).find("div").html(number * currentRow.StandardSalesPrice * (currentRow.DiscountRate / 100));
                            }
                            if ($(this).attr("field") == "TaxAmount") {
                                $(this).find("div").html(parseFloat((number * currentRow.StandardSalesPrice) * (1 - (100 / (parseFloat(taxRate) + 100)))).toFixed(2));
                            }
                            if ($(this).attr("field") == "UnTaxAmount") {
                                $(this).find("div").html((number * currentRow.StandardSalesPrice * (1 - currentRow.DiscountRate / 100)) - parseFloat((number * currentRow.StandardSalesPrice) * (1 - (100 / (parseFloat(taxRate) + 100)))).toFixed(2));
                            }
                        });
                        $('#selectedStocksForSalesOrder').datagrid('unselectRow', currentIndex);
                        currentRow.Number = number;

                    })
                }
                else if (e.field == "TaxRate") {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function () {
                        $('#selectedStocksForSalesOrder').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function () {
                        taxRate = $(this).val();
                        currentIndex = $(this).attr("selectedStockRowIndex");
                        currentRow = $('#selectedStocksForSalesOrder').datagrid('getSelected');
                        rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "Number") {
                                number = $(this).find("input").val();
                            }
                            if ($(this).attr("field") == "TaxAmount") {
                                $(this).find("div").html(parseFloat((number * currentRow.StandardSalesPrice) * (1 - (100 / (parseFloat(taxRate) + 100)))).toFixed(2));
                            }
                        });
                        $('#selectedStocksForSalesOrder').datagrid('unselectRow', currentIndex);
                        currentRow.TaxRate = taxRate;
                    })
                }
            }
        }

        $("form[action^='/salesorder/add']").submit(function () {
            var rows = $('#selectedStocksForSalesOrder').datagrid('getRows');
            salesOrderDetails = "[";
            for (var i = 0; i < rows.length; i++) {
                if (i == (rows.length - 1)) {
                    salesOrderDetails = salesOrderDetails + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, \"Number\" : " + rows[i].Number + ", \"UnitCost\" :" + rows[i].StandardSalesPrice + ", \"TaxRate\" :" + rows[i].TaxRate + " }";
                }
                else {
                    salesOrderDetails = salesOrderDetails + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, \"Number\" : " + rows[i].Number + ", \"UnitCost\" :" + rows[i].StandardSalesPrice + ", \"TaxRate\" :" + rows[i].TaxRate + " }" + ",";
                }
            }
            salesOrderDetails = salesOrderDetails + "]";
            $("#salesOrderDetails").val(salesOrderDetails);
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (data) {
                    if (data.IsSuccess) {
                        alert(data.Messages[0]);
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#closeOrOpen").bind("click", function () {
            var url = '/purchaseorder';
            if ($(this).val() == '关闭订单') {
                url = url + '/close/' + $("#code").val();
            }
            else {
                url = url + '/open/' + $("#code").val();
            }
            $.ajax({
                url: url,
                type: 'Post',
                success: function (data) {
                    if (data.IsSuccess) {
                        alert(data.Messages[0]);
                        if ($("#closeOrOpen").val() == '关闭订单') {
                            $("#closeOrOpen").val('打开订单')
                        }
                        else {
                            $("#closeOrOpen").val('关闭订单')
                        }
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })
        });

        $("#customerCodeForSalesOrder").bind("click", function () {
            InitSelectCustomer('customersForSalesOrder');
            openWindow("selectCustomerWindowForSalesOrder");
        });

        $("#searchCustomerForSalesOrder").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#customersForSalesOrder').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectCustomerForSalesOrder").bind("click", function () {
            var currentRow = $('#customersForSalesOrder').datagrid('getSelected');
            $("#customerCodeForSalesOrder").val(currentRow.Id);
            $("#customerNameForSalesOrder").val(currentRow.Name);
            closeWindow("selectCustomerWindowForSalesOrder");
        });

        $("#wareHouseAddressForSalesOrder").bind("click", function () {
            InitSelectWareHouse('wareHousesForSalesOrder');
            openWindow("selectWareHouseWindowForSalesOrder");
        });

        $("#searchWareHouseForSalesOrder").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#wareHousesForSalesOrder').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectWareHouseForSalesOrder").bind("click", function () {
            var currentRow = $('#wareHousesForSalesOrder').datagrid('getSelected');
            $("#wareHouseCodeForSalesOrder").val(currentRow.Id);
            $("#wareHouseAddressForSalesOrder").val(currentRow.Address);
            closeWindow("selectWareHouseWindowForSalesOrder");
        });

        $("#saleEmployeeCodeForSalesOrder").bind("click", function () {
            InitSelectEmployee('employeesForSalesOrder');
            openWindow("selectEmployeeWindowForSalesOrder");
        });

        $("#searchEmployeeForSalesOrder").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#employeesForSalesOrder').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectEmployeeForSalesOrder").bind("click", function () {
            var currentRow = $('#employeesForSalesOrder').datagrid('getSelected');
            $("#saleEmployeeCodeForSalesOrder").val(currentRow.Id);
            $("#saleEmployeeNameForSalesOrder").val(currentRow.Name);
            closeWindow("selectEmployeeWindowForSalesOrder");
        });

    });
</script>
